<template>
  <div>
    <el-dialog :title="title" :visible.sync="visible" :close-on-click-modal="false" @open="handleOpen" @close="handleClose">
      <el-form ref="ad" :model="ad" label-position="top" :rules="rules">
        <!-- <el-form-item label="广告编号">
          <el-input v-model="ad.adId" autocomplete="off" readonly="" />
        </el-form-item> -->
        <el-form-item prop="adName" label="广告名称">
          <el-input v-model="ad.adName" autocomplete="off" maxlength="50" show-word-limit />
        </el-form-item>
        <!-- <el-form-item label="广告类型">
          <el-input v-model="ad.adType" autocomplete="off" />
        </el-form-item> -->
        <el-form-item prop="adType" label="广告类型">
          <el-select v-model="ad.adType">
            <el-option key="1" label="服务项目广告" value="1" />
            <el-option key="2" label="第三方广告" value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="广告图片">

          <el-upload
            class="avatar-uploader"
            name="files"
            :action="url"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="imageUrl" :src="imageUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon" />
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过2MB,建议上传340*150的图片</div>
          </el-upload>
          <!-- <img v-if="type==2" :src="ad.adImg" width="200px" height="120px"> -->
        </el-form-item>

        <el-form-item prop="adLessonId" label="广告机构">
          <el-select v-model="ad.adLessonId" placeholder="请选择">
            <el-option
              v-for="item in lesson"
              :key="item.orgId"
              :value="item.orgId"
              :label="item.orgName"
            />
          </el-select>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button v-if="type==2" type="primary" @click="handleUpdate('ad')">修 改</el-button>
        <el-button v-if="type==1" type="primary" @click="handleAdd('ad')">添 加</el-button>
        <el-button @click="visible=false">返 回</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getAdById, addAd, updateAd } from '@/api/ad'
import { getAllOrg } from '@/api/org'
export default {
  components: {},
  props: {
    id: {
      default: 0,
      type: Number
    },
    visible: {
      default: false,
      type: Boolean
    },
    // 添加 1  更新 2
    type: {
      default: 0,
      type: Number
    },
    title: {
      default: '',
      type: String
    }
  },
  data() {
    var checkChinese = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入银行名称'))
      } else if (!this.isChinese(value)) { // 引入methods中封装的检查手机格式的方法
        callback(new Error('请输入中文!'))
      } else {
        callback()
      }
    }
    return {
      url: process.env.VUE_APP_BASE_API + 'file/',
      ad: {},
      lesson: {},
      imageUrl: '',
      rules: {
        adName: [{ required: true, message: '广告名称不能为空', trigger: 'blur' }, { validator: checkChinese, trigger: ['blur', 'change'] }],
        adType: [{ required: true, message: '广告类型不能为空', trigger: 'blur' }],
        adLessonId: [{ required: true, message: '广告机构不能为空', trigger: 'blur' }]
      }
    }
  },
  created() {
    this.fetchData()
  },
  methods: {
    handleAvatarSuccess(res, file) {
      this.imageUrl = res.obj.split(';')[0]
      this.ad.adImg = this.imageUrl
    },
    beforeAvatarUpload(file) {
      // const isJPG = file.type === 'image/jpeg'
      const isImage = file.type === 'image/png' || file.type === 'image/jpg' || file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isImage) {
        this.$message.error('上传图片只能是 JPG或PNG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!')
      }
      return isImage && isLt2M
      // return true
    },
    fetchData() {
      getAllOrg().then((resp) => {
        this.lesson = resp.obj
      })
    },

    handleOpen() {
      if (this.type === 2) {
        console.log('fatch data')
        getAdById(this.id).then((resp) => {
          this.ad = resp.obj
          this.imageUrl = resp.obj.adImg
        })
      }
    },

    handleAdd(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          addAd(this.ad).then((resp) => {
            this.$notify({
              title: '添加成功',
              type: 'success'
            })
            this.$parent.fetchData()
          })
          this.visible = false
          return true
        } else {
          this.$notify({
            title: '请正确填写',
            type: 'error'
          })
          return false
        }
      })
    },

    handleUpdate(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          updateAd(this.ad).then((resp) => {
            this.$notify({
              title: '更新成功',
              type: 'success'
            })
            this.$parent.fetchData()
          })
          this.visible = false
          return true
        } else {
          this.$notify({
            title: '请正确填写',
            type: 'error'
          })
          return false
        }
      })
    },

    handleClose() {
      console.log('eeeeee')
      this.$emit('close', {})
      this.ad = {}
      this.imageUrl = ''
    },
    isChinese(val) {
      if (/[^\u4E00-\u9FA5]/.test(val)) {
        return false
      } else {
        return true
      }
    },

    // 特殊字符过滤
    checkSpecificKey(str) {
      var specialKey = "[`~!#$^&*()=|{}':;',\\[\\].<>/?~！#￥……&*（）——|{}【】‘；：”“'。，、？]‘'"
      for (var i = 0; i < str.length; i++) {
        if (specialKey.indexOf(str.substr(i, 1)) !== -1) {
          return false
        }
      }
      return true
    },

    // 验证字符串
    validateFontSize(rule, value, callback) {
      if (value.length < 30) {
        callback()
      } else {
        callback(new Error('字符串长度在1-30之间'))
      }
    },

    // 验证字符串
    validateCharacter(rule, value, callback) {
      if (this.checkSpecificKey(value)) {
        callback()
      } else {
        callback(new Error('请不要输入特殊字符'))
      }
    }
  }
}
</script>

<style>
 .avatar-uploader .el-upload {
        border: 1px dashed #d9d9d9;
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
      }
    .avatar-uploader .el-upload:hover {
      border-color: #409EFF;
    }
    .avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 340px;
      height: 150px;
      line-height: 150px;
      text-align: center;
    }
    .avatar {
      width: 340px;
      height: 150px;
      display: block;
    }
</style>
